<template>
    <div class="duixian_charts">
        <div class="charts" :style="gettt()">
            <template v-if="showecharts">
                <div ref="echart" style="width: 100%; height: 100%"></div>
            </template>

        </div>
    </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, ref, defineExpose } from "vue";
// import { defineComponent, expose } from 'vue';



const { monitorStore, monitorState } = inject('MonitorStore')

const echart = ref(null)
const showecharts = ref(true)
const indexdfg = ref(1)

const intervalIdPict = ref(null)

const bctypeColors = ref({
    hga: '#e64d4d',
    ps3838: '#e88d0d',
    kaiyun: '#46a2ea',
    manbet165: '#48a66b',
    imsport: '#0fc4c2',
    isn: '#666666'
})

const gettt = () => {
    let a = echartsRawData
    // getEcharts()
    return ''
}
const echartsRawData = computed(() => {
    let data = []
    let data2 = {
        header: [],
        data2: [],
        data: []
    }
    monitorState.chartmodule.checkpicturelist.forEach(item => {
        let value = monitorState.chartmodule.activeHandicaps[item].childrens[monitorState.chartmodule.activeHandicaps[item].activetab].index_data[monitorState.chartmodule.activeTime][monitorState.chartmodule.activeHandicaps[item].active]
        data.push(value)
    });




    data.forEach(item => {
        let a = []
        item.forEach(item2 => {
            data2.header.push(item2.date)
            a.push(item2.odd)
        });
        data2.data.push(a)
    });

    return data2


})

function splitData(rawData) {
    let categoryData = [];
    let values = [];
    let volumes = [];
    for (let i = 0; i < rawData.length; i++) {
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i]);
        volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
    }
    return {
        categoryData: categoryData,
        values: values,
        volumes: volumes
    };
}
function calculateMA(dayCount, data) {
    var result = [];
    for (var i = 0, len = data.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += data.values[i - j][1];
        }
        result.push(+(sum / dayCount).toFixed(3));
    }
    return result;
}

const getEcharts = (server, header) => {
    if (echart.value) {

        let rawData = []
        const myChart = echarts.init(echart.value)
        // 绘制图表
        // var data = monitorState.chartmodule.data;
        const upColor = '#00da3c';
        const downColor = '#ec0000';



        let option = {
            animation: false,
            title: {
                text: '成交量(Volume)',  // 设置柱状图的标题
                left: '3%',
                top: '69%',          // 标题距离顶部10px
                textStyle: {
                    fontSize: 12,      // 标题字体大小
                    color: '#8a8a8a'      // 标题颜色
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                },
                borderWidth: 1,
                borderColor: '#ccc',
                padding: 10,
                textStyle: {
                    color: '#000'
                },
                formatter: (params) => {
                    // 自定义弹窗内容

                    let tooltipContent = '<div>';

                    params.forEach((item, index) => {

                        // 对每一个系列的项进行格式化处理
                        if (item.seriesName == '时间') {
                            tooltipContent += `
                    <div style="display: flex">
                        <div>时间：</div>
                        <div>${item.axisValue}</div>
                    </div>
                `;
                        } else {
                            if (monitorState.chartmodule.activeHandicaps[monitorState.chartmodule.checkpicturelist[index]] != undefined && item.value != '') {
                                tooltipContent += `
                    <div style="display: flex">
                        <div>${monitorState.bctypesObj[monitorState.chartmodule.checkpicturelist[index]]}(${monitorState.chartmodule.activeHandicaps[monitorState.chartmodule.checkpicturelist[index]].activevalue || ''})：</div>
                        <div>${item.value}</div>
                    </div>
                `;
                            }
                        }


                    });
                    tooltipContent += '</div>';
                    return tooltipContent;  // 返回自定义的 HTML 内容
                }
            },
            axisPointer: {
                link: [
                    {
                        xAxisIndex: 'all'
                    }
                ],
                label: {
                    backgroundColor: '#777'
                },
                tooltip: {
                    show: false  // 禁用指示线的 tooltip，确保不显示坐标值
                }
            },
            visualMap: {
                show: false,
                seriesIndex: 5,
                dimension: 2,
                pieces: [
                    {
                        value: 1,
                        color: downColor
                    },
                    {
                        value: -1,
                        color: upColor
                    }
                ]
            },
            grid: [
                {
                    left: '0',
                    top: '5%',
                    right: '6%',
                    height: '64%'
                },
                {
                    left: '0',
                    right: '6%',
                    top: '69%',
                    height: '22%'
                }
            ],
            xAxis: [
                {
                    type: 'category',
                    data: header,
                    boundaryGap: true,
                    axisTick: { show: false },
                    axisLabel: { show: false },
                    min: 'dataMin',
                    max: 'dataMax',
                    axisPointer: {
                        z: 10
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: '#8a8a8a',
                            width: 1,
                            type: 'solid',
                            opacity: 0.3
                        },
                        // symbol: ['none', 'rect'],
                        // symbolSize: [1, 200],
                        // symbolOffset: [0, 100],
                        itemStyle: {
                            color: '#8a8a8a',
                            opacity: 0.3
                        }
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'solid',
                            color: '#ebebeb',
                            width: 1,
                            opacity: 0.3
                        }
                    },
                    

                },
                {
                    type: 'category',
                    gridIndex: 1,
                    data: header,
                    boundaryGap: true,
                    min: 'dataMin',
                    max: 'dataMax',
                    axisPointer: {
                        z: 10
                    },

                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: '#8a8a8a',
                            width: 1,
                            type: 'solid',
                            opacity: 0.3
                        }
                    },
                    axisTick: { show: false },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'solid',
                            color: '#ebebeb',
                            width: 1,
                            opacity: 0.3
                        }
                    },

                }
            ],
            yAxis: [
                {
                    type: 'value',
                    scale: true,
                    position: 'right',
                    max: 'dataMax',
                    boundaryGap: true,
                    axisLabel: {
                        formatter: function (value) {

                            const [minValue, maxValue] = myChart.getModel().getComponent('yAxis').axis.scale.getExtent();

                            // 如果当前值是最小值或最大值，则返回空，隐藏它们
                            if (value === minValue) {
                                return '';
                            }
                            return value;
                        }
                    },
                    axisLine: {
                        show: true,
                        length: 100,
                        lineStyle: {
                            color: '#8a8a8a',
                            width: 1,
                            type: 'solid',
                            opacity: 0.3
                        },

                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'solid',
                            color: '#ebebeb',
                            width: 1,
                            opacity: 0.3
                        }
                    },
                    axisTick: {
                        show: false
                        // interval: function (index, value) {
                        //     return value == 10 ? null : null;
                        // }
                    },


                },
                {
                    type: 'value',
                    scale: true,
                    position: 'right',
                    min: 0,
    //                 max: function(value) {
    //   return value.max + (value.max - value.min) * 0.1;
    // },
                    boundaryGap: ['0%', '15%'],
                    gridIndex: 1,
                    splitNumber: 2,
                    axisLabel: {
                        formatter: function (value,index) {
                            const [minValue, maxValue] = myChart.getModel().getComponent('yAxis').axis.scale.getExtent();
                            if (value === 0 || index == 3) {
                                return '';
                            }
                            return value;
                        }
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: '#8a8a8a',
                            width: 1,
                            type: 'solid',
                            opacity: 0.3
                        }
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'solid',
                            color: '#ebebeb',
                            width: 1,
                            opacity: 0.3
                        }
                    }
                }
            ],
            dataZoom: [
                {
                    type: 'inside',
                    xAxisIndex: [0, 1],
                    start: 5,
                    end: 100
                },
                {
                    show: false,
                    xAxisIndex: [0, 1],
                    type: 'slider',
                    top: '85%',
                    start: 5,
                    end: 100
                }
            ],
            series: server
        }
        myChart.dispatchAction({
            // type: 'brush',
            // areas: [
            //     {
            //         brushType: 'lineX',
            //         coordRange: ['2025-01-20 00:21:30', '2025-01-21 15:13:36'],
            //         xAxisIndex: 0
            //     }
            // ]
        });
        myChart.setOption(option, { notMerge: true })
    }


}

const updateChart = () => {
    // console.log(monitorState.picturedata);
    
    let server = []
    let header = []
    let c = []
    if (monitorState.chartmodule.checkpicturelist.length > 0) {
        let lookindex = {
            index: 0,
            length: 0
        }

        monitorState.chartmodule.checkpicturelist.forEach((item2, index2) => {
            monitorState.picturedata.forEach((item, index) => {
                if (item2 == item.bc_type) {
                    if (item.data.length > lookindex.length) {
                        lookindex = {
                            index: index,
                            length: item.data.length
                        }
                    }
                    let a = {
                        name: '指数',
                        type: 'line',
                        data: extractOdds(item.data),
                        symbol: 'none',
                        smooth: true,
                        date: Date.now(),
                        lineStyle: {
                            opacity: 0.5
                        },
                        itemStyle: {
                            color: bctypeColors.value[item.bc_type]
                        }
                    }
                    c.push(a)
                }

            });
        });


        // if (lookindex.length != 100) {

        // } else {
            c.forEach(item => {
                if (item.data.length != lookindex.length) {
                    let b = []
                    for (let i = 0; i < (lookindex.length - item.data.length); i++) {
                        b.push('')
                    }
                    item.data = [...b, ...item.data]
                }
            });
        // }
        server = c
        monitorState.picturedata[lookindex.index].data.forEach(item => {
            header.push(item.time)
        });

        server.unshift({
            name: 'Dow-Jones index',
            type: 'candlestick',
            data: extractOdds(monitorState.picturedata[lookindex.index].data),
            itemStyle: {
                color: undefined,
                color0: undefined,
                borderColor: undefined,
                borderColor0: undefined
            }
        })

        server.push({
            name: '时间',
            type: 'line',
            symbol: 'none',
            smooth: true,
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: extractOdds(monitorState.picturedata[lookindex.index].data)
        })
    }
    // console.log(server);
    
    getEcharts(server, header)

    // if (server.length > 1) {
    //     intervalIdPict.value = setInterval(() => monitorStore.getpicturedata(false), 5000)
    // }




};
function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function extractOdds(arr) {
    let a = arr.map(obj => obj.odds || null);
    // if (a.length < 100) {
    // let b = []
    // for (let i = 0; i < (100 - a.length); i++) {
    //     b.push('')
    // }
    // a = [...b,...a]
    // }
    return a // 如果 odds 不存在，返回 null
}


onMounted(() => {
    getEcharts()


})

watch(monitorState.chartmodule.data, (newValue) => {
    // getEcharts()

});

defineExpose({
    getEcharts,
    updateChart
});
</script>

<style lang="scss" scoped>
.duixian_charts {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    
}

.charts {
    width: 100%;
    height: 100%;
    // background: red;
}
</style>